package com.zymail.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zymail.bean.ZyAssign;
import com.zymail.bean.ZyTicket;
import com.zymail.service.ZyAssignService;
import com.zymail.service.ZyTicketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@RestController
@RequestMapping("/ticket")
public class TicketController extends BaseController {
    @Autowired
    public ZyTicketService ticketService;

    @Autowired
    public ZyAssignService assignService;

    /**
     * 得到自己的所有优惠卷
     * @param session_key   session_key
     * @return  List<ticket>
     */
    @RequestMapping("/getmyticket/{session_key}")
    public List<ZyTicket> getmyticket(@PathVariable("session_key") String session_key){
        Integer userId = get_userId(session_key);
        if(userId == 0) return null;

        QueryWrapper<ZyAssign> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("is_use", 0);
        List<ZyAssign> assignList =  assignService.list(wrapper);

        ArrayList<ZyTicket> ticketList = new ArrayList<>();

        LocalDateTime now = LocalDateTime.now();
        for (ZyAssign assign: assignList) {
            LocalDateTime time = assign.getTicket().getTime();
            if(now.isBefore(time)){
                ticketList.add(assign.getTicket());
            }
        }

        ticketList.sort((ZyTicket ticket1, ZyTicket ticket2) -> ticket2.getPrice().compareTo(ticket1.getPrice()));

        return ticketList;
    }


    /**
     * 使用优惠卷
     * @param session_key session_key
     * @param ticketId  分配的id
     * @return  boolean
     */
    @PutMapping("/usemyticket/{session_key}/{ticketId}")
    public boolean usemyticket(@PathVariable("session_key") String session_key,
                               @PathVariable("ticketId") Integer ticketId){
        Integer userId = get_userId(session_key);
        if(userId == 0) return false;

        QueryWrapper<ZyAssign> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("ticket_id", ticketId);

        ZyAssign assign = assignService.getOne(wrapper);
        if(assign.getIsUse() == 1) return false;
        if(!assign.getUserId().equals(userId)) return false;

        assign.setIsUse(1);
        assign.setUser(null);
        assign.setTicket(null);

        return assignService.updateById(assign);
    }
}
